//
// Created by Elyar Anwar on 2024/9/21.
//

#include "oled.h"
#include "esp_log.h"
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include "u8g2.h"
#include "u8x8.h"

#define OLED_SCK GPIO_NUM_18
#define OLED_SDA GPIO_NUM_23
#define OLED_RST GPIO_NUM_4
#define OLED_DC GPIO_NUM_21

u8g2_t u8g2;

static void gpio_init() {
//    初始化gpio引脚
    gpio_config_t gpioConfig = {
            .pin_bit_mask = (1ULL << OLED_SCK) | (1ULL << OLED_SDA) | (1ULL << OLED_RST) | (1ULL << OLED_DC),
            .mode = GPIO_MODE_OUTPUT,
            .pull_down_en = GPIO_PULLDOWN_DISABLE,
            .pull_up_en = GPIO_PULLUP_DISABLE,
            .intr_type = GPIO_INTR_DISABLE
    };
    gpio_config(&gpioConfig);
}

uint8_t gpio_and_delay_callback(u8x8_t *u8x8, uint8_t msg, uint8_t arg_int, void *arg_ptr) {
    switch (msg) {
        case U8X8_MSG_GPIO_AND_DELAY_INIT:
            gpio_init();
            break;
        case U8X8_MSG_GPIO_RESET:
            gpio_set_level(OLED_RST, arg_int);
            break;
        case U8X8_MSG_GPIO_DC:
            gpio_set_level(OLED_DC, arg_int);
            break;
        case U8X8_MSG_GPIO_SPI_CLOCK:
            gpio_set_level(OLED_SCK, arg_int);
            break;
        case U8X8_MSG_GPIO_SPI_DATA:
            gpio_set_level(OLED_SDA, arg_int);
            break;
        case U8X8_MSG_DELAY_MILLI:
            vTaskDelay(arg_int / portTICK_PERIOD_MS);
            break;
        case U8X8_MSG_GPIO_MENU_HOME:
            ESP_LOGI("OLED", "U8X8_MSG_GPIO_MENU_HOME");
            break;
        default:
            return 0;
    }
    return 1;
}


void oled_init() {
    //初始化OLED
    u8g2_Setup_ssd1306_128x64_noname_f(&u8g2, U8G2_R0, u8x8_byte_4wire_sw_spi, gpio_and_delay_callback);
    u8g2_InitDisplay(&u8g2);//初始化显示器
    u8g2_SetPowerSave(&u8g2, 0);//唤醒显示器
    u8g2_ClearBuffer(&u8g2);//清除缓冲区
}

void test_screen() {
    u8g2_SetFont(&u8g2, u8g2_font_6x12_mr);
    u8g2_DrawStr(&u8g2, 0, 30, "hello world");
    u8g2_SendBuffer(&u8g2);        // 一定要发送buffer
}

void show_content(const char *content) {
    u8g2_ClearBuffer(&u8g2);
    u8g2_SetFont(&u8g2, u8g2_font_6x12_mr);
    u8g2_DrawStr(&u8g2, 0, 30, content);
    u8g2_SendBuffer(&u8g2);        // 一定要发送buffer
}
